package com.bawei.module_vehicle.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.Router
import com.bawei.lib_common.base.state.Failed
import com.bawei.lib_common.base.state.Loading
import com.bawei.lib_common.base.state.Success
import com.bawei.module_vehicle.R
import com.bawei.module_vehicle.databinding.FragmentCarBinding
import com.bawei.module_vehicle.model.CarModel
import com.bawei.module_vehicle.ui.adapter.CarAdapter
import com.bawei.myclub.base.mvvm.view.BaseFragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * 车辆管理 Fragment
 * 完全对齐 NoticeFragment 写法：
 * 1. 注解：@AndroidEntryPoint + @Route
 * 2. 继承 BaseFragment<ViewModel, Binding>
 * 3. viewModels() 初始化 ViewModel
 * 4. 使用 lifecycleScope 收集 Flow 状态
 * 5. 路由、数据绑定、状态监听与公告模块一致
 */
@AndroidEntryPoint
class CarFragment : Fragment() {

    private var _binding: FragmentCarBinding? = null
    private val binding get() = _binding!!
    private val viewModel: CarViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentCarBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupSearch()
        observeData()
        binding.top.tvLogo.setOnClickListener {
            requireActivity().finish()
        }
    }

    private fun setupSearch() {
        binding.ivSearch.setOnClickListener {
            val idStr = binding.etSearchId.text.toString().trim()
            if (idStr.isNotEmpty()) {
                val id = idStr.toLongOrNull()
                id?.let {
                    viewModel.searchVehicleById(it)
                } ?: run {
                    showEmptyState("请输入有效的数字ID")
                }
            } else {
                showEmptyState("请输入车辆ID")
            }
        }
    }

    private fun observeData() {
        lifecycleScope.launch {
            viewModel.uiState.collect { state ->
                when (state) {
                    CarViewModel.UiState.Idle -> {
                        hideAllStates()
                    }
                    CarViewModel.UiState.Loading -> {
                        hideAllStates()

                    }
                    CarViewModel.UiState.Success -> {
                        hideAllStates()
                        viewModel.car.value?.let { car ->
                            showCarInfo(car)
                        } ?: run {
                            showEmptyState("未找到车辆信息")
                        }
                    }
                    is CarViewModel.UiState.Failed -> {
                        hideAllStates()
                        showEmptyState(state.errorMsg)
                    }
                }
            }
        }
    }

    private fun showCarInfo(car: CarModel) {
        binding.carInfoCard.cvCarInfo.visibility = View.VISIBLE
        binding.carInfoCard.tvLicensePlate.text = car.licensePlate
        binding.carInfoCard.tvOwnerModel.text = car.ownerName
        binding.carInfoCard.tvEntryTime2.text = "09:30"
        binding.carInfoCard.tvParkingDuration.text = "已停:3小时"
        binding.carInfoCard.tvParkingSpace.text = "A区-12号"
    }

    private fun showEmptyState(message: String) {
        binding.emptyStateLayout.visibility = View.VISIBLE

    }

    private fun hideAllStates() {
        binding.carInfoCard.cvCarInfo.visibility = View.GONE
        binding.emptyStateLayout.visibility = View.GONE

    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}